import { Checkbox, Col, Form, Input, Row } from 'antd';
import React, { forwardRef, useState, useCallback } from 'react';

/**
 * @param {[{key, title}]} dataList []
 */
const BoxInput = forwardRef(
    ({
        dataList = [],
        form,
        itemField,
        checkKey = 'checkKey',
        inputKey = 'inputKey',
        validateTitle = '',
        placeholder = '请输入'
    }) => {
        const { getFieldDecorator, setFieldsValue } = form;
        const newModelKey = `__${itemField}__.`;

        const [value, setValue] = useState([]);
        const getItem = useCallback(key => value.find(item => item[checkKey] === key), [value]);
        const disableState = useCallback(key => !getItem(key), [getItem]);
        const toggleSelect = useCallback(
            (checked, checkValue, inputValue) => {
                let result;

                if (checked) {
                    const oldValue = getItem(checkValue);

                    // 已经存在，做更新动作
                    if (oldValue) {
                        result = value.map(item => ({
                            ...item,
                            ...(item[checkKey] === checkValue ? { [inputKey]: inputValue } : null)
                        }));
                    } else {
                        // 做新增操作
                        result = [].concat(value).concat({ [checkKey]: checkValue, [inputKey]: inputValue || '' });
                    }
                } else {
                    result = value.filter(item => item[checkKey] !== checkValue);
                    // 清空文本框值
                    setFieldsValue({ [`${newModelKey}${checkValue}.content`]: '' });
                }
                setValue(result);
                setFieldsValue({
                    [itemField]: result
                });
            },
            [getItem, value]
        );

        return (
            <>
                {getFieldDecorator(
                    itemField,
                    {}
                )(
                    <>
                        {dataList.map(item => (
                            <div key={item.key}>
                                <Row>
                                    <Col span={9}>
                                        <Form.Item>
                                            {getFieldDecorator(`${newModelKey}${item.key}.checked`, {
                                                valuePropName: 'checked',
                                                initialValue: false
                                            })(
                                                <Checkbox
                                                    onChange={e => {
                                                        toggleSelect(e.target.checked, item.key, '');
                                                    }}
                                                    style={{
                                                        display: 'block',
                                                        overflow: 'hidden',
                                                        'text-overflow': 'ellipsis',
                                                        'word-break': 'break-all',
                                                        'white-space': 'nowrap'
                                                    }}
                                                >
                                                    <span title={item.title}>{item.title}</span>
                                                </Checkbox>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={15}>
                                        <Form.Item>
                                            {getFieldDecorator(`${newModelKey}${item.key}.content`, {
                                                initialValue: '',
                                                rules: [
                                                    {
                                                        required: !disableState(item.key),
                                                        message: `${validateTitle}不能为空`
                                                    },
                                                    {
                                                        max: 50,
                                                        message: `${validateTitle}不能超过50个字符`
                                                    }
                                                ]
                                            })(
                                                <Input
                                                    placeholder={placeholder}
                                                    disabled={disableState(item.key)}
                                                    onChange={e => {
                                                        toggleSelect(true, item.key, e.target.value);
                                                    }}
                                                    maxLength={50}
                                                />
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        ))}
                    </>
                )}
            </>
        );
    }
);

export default BoxInput;
